package com.tydic.test_ws.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tydic.webservice.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/test_ws")
public class TestWsController {
    WebServiceDemoService_Service demoService_service = new WebServiceDemoService_Service();
    WebServiceDemoService wsService = demoService_service.getWebServiceDemoServiceImplPort();

    //新建ObjectMapper对象
    ObjectMapper objectMapper = new ObjectMapper();

    @GetMapping("/hello/{name}")
    public String hello(@PathVariable("name")String name){

        String hello = wsService.testString(name);
        return hello;
    }

    @GetMapping("/testMap")
    public Provider testMap(){

        Customer customer = new Customer();
        customer.setSuccess(true);
        customer.setName("customer");
        customer.setMessage("webservice客户端调用服务端方法");
        Provider provider = wsService.testObject(customer);
        return provider;
    }

    @GetMapping("/testJson")
    public Object testJson(){
        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        map.put("message", "webservice客户端调用服务端方法");

        TestJsonResponse.Return result = null;
        try {
            String json = objectMapper.writeValueAsString(map);//map转string
            result = wsService.testJson(json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        List<TestJsonResponse.Return.Entry> entry = result.getEntry();
        for (TestJsonResponse.Return.Entry testJsonResponse: entry) {
            System.out.println(">>>>>>>>>>>key: " + testJsonResponse.getKey());
            System.out.println(">>>>>>>>>>>value: " + testJsonResponse.getValue());
        }
        return result;
    }

    @GetMapping("/testJsonStr")
    public Map<String, Object> testJsonStr(){
        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        map.put("message", "webservice客户端调用服务端方法");

        try {
            String json = objectMapper.writeValueAsString(map);//map转string
            String jsonStr = wsService.testJsonStr(json);
            return objectMapper.readValue(jsonStr, Map.class);//string转map
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}
